<template>
  <div class='search'>
    <van-nav-bar
      title='搜索中心'
      left-arrow
      @click-left='$router.back()'
    ></van-nav-bar>
    <!-- 搜索框 -->
    <van-search
      v-model='keyword'
      show-action
      shape='round'
      placeholder='请输入搜索关键词'
      @search='onSearch(keyword)'
      @input='onInput'
    >
      <template #action>
        <div @click='onSearch(keyword)'>搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group v-if='keyword'>
      <!--给cell去设置title，span标签不会被识别出来-->
      <!--  :title='highLight(item,value)'-->
      <van-cell
        icon='search'
        v-for='item in sugList'
        :key='item'
      >
        <span v-html='highLight(item,keyword)'></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title='历史记录'></van-cell>
      <van-cell
        @click='onSearch(item)'
        :title='item'
        v-for='item in historyList'
        :key='item'>
        <van-icon name='close' @click.stop='del(item)' />
      </van-cell>
    </van-cell-group>
    <!--空状态提示-->
    <van-empty
      image='search'
      description='暂无搜索结果'
      v-if='sugList.length===0 && keyword'
    />
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
import {
  setStorageSearchHistory,
  getStorageSearchHistory
} from '@/utils/storage'

export default {
  name: 'Search',
  data () {
    return {
      keyword: '',
      // 搜索建议列表
      sugList: [],
      // 历史记录
      historyList: getStorageSearchHistory()
    }
  },
  methods: {
    onSearch (item) {
      console.log(this.keyword, '搜索中')
      // 将搜索的关键字添加到历史记录中
      // 1. 判断是否已经存在并删除
      this.historyList = this.historyList.filter(i => i !== item)
      // 2. 添加到数组的最前面
      this.historyList.unshift(item)
      console.log(this.historyList)
      // 存到本地
      setStorageSearchHistory(this.historyList)
      // 跳转到搜索结果页面
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: item
        }
      })
    },
    onInput () {
      // 无数据返回
      if (!this.keyword) return
      // 使用防抖优化频繁触发的效果
      clearTimeout(this.timerId)
      this.timerId = setTimeout(async () => {
        // 获取搜索建议
        const { data: res } = await getSearchSuggestion(this.keyword)
        console.log(res)
        // 如果返回的数据为空，就不显示高亮
        if (res.options[0] === null) {
          return (this.sugList = [])
        }
        // 放入数据
        this.sugList = res.options
      }, 500)
    },
    del (item) {
      // 删除历史记录
      this.historyList = this.historyList.filter(i => i !== item)
      // 存到本地
      setStorageSearchHistory(this.historyList)
    },
    // 高亮
    highLight (str, keyword) {
      const reg = new RegExp(keyword, 'gi')
      return str.replace(reg, match => {
        return `<span style='color: red;'>${match}</span>`
      })
    }
  }
}
</script>

<style scoped>

</style>
